<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>memory的设计</title>
</head>
<body>
    <script>
        /**
         * 问题：
         * 1：如何取到上一个参数
         * 2：add后如何执行
         * 
         * memory 的设计思路
         * 1.fire 执行时，将当前的参数缓存下来 memory
         * 2.每次执行add方法，先判断 memory 是否存在
         *   2.1 存在缓存值，取当前list里最后一个fn，执行
        */

        var Callback = function(options) {
            var list = [],
                self,
                firingStart,
                memory;
            
            function _fire(args) {
                memory = options === 'memory' && args;
                var length = list.length;
                firingIndex = firingStart || 0;
                firingStart = 0
                for (; firingStart < length; firingStart++) {
                    list[firingStart](args);
                }
            }

            self = {
                add: function(fn) {
                    var start = list.length
                    list.push(fn)
                    // 使用缓存值，执行一次 _fire 方法
                    if(memory) {
                        firingStart = start
                        _fire(memory)
                    }
                },
                fire: function(args) {
                    if(list) {
                        _fire(args)
                    }
                }
            }
            return self
        }


        function test1(data) {
            console.log('test1~~~~',data)
        }
        function test2(data) {
            console.log('test2~~~~',data)
        }

        var cbs = Callback('memory')
        cbs.add(test1)
        cbs.fire('hahaha') // test1~~~~ hahaha
        cbs.add(test2)  // test2~~~~ hahaha
        cbs.fire('kakak') 
    </script>
</body>
</html>